import { Inject, Injectable } from '@nestjs/common';
import { PrismaService } from 'src/prisma/prisma.service';
import { Message } from '@prisma/client';
export type PartMessage = Pick<
  Message,
  'roomId' | 'senderId' | 'type' | 'content'
>;

@Injectable()
export class MessageService {
  @Inject(PrismaService)
  private prismaService: PrismaService;

  // 获取聊天室聊天记录
  async list(roomId: number) {
    // 查找该房间所有消息
    const messages = await this.prismaService.message.findMany({
      where: {
        roomId: roomId,
      },
    });
    console.log('消息', messages);

    // 查找每条聊天对应的发送者信息，并于消息合并一起
    const result = [];
    for (let i = 0; i < messages.length; i++) {
      const user = await this.prismaService.user.findUnique({
        where: {
          id: messages[i].senderId,
        },
        select: {
          id: true,
          username: true,
          nickName: true,
          email: true,
          createTime: true,
          avatar: true,
        },
      });

      result.push({
        ...messages[i],
        sender: user,
      });
    }

    return result;
  }

  async add(roomId: number, message: PartMessage) {
    return this.prismaService.message.create({
      data: message,
    });
  }
}
